package com.usc.csci588.chaltrojan.photoupload;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ResponseHeaderOverrides;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;

public class MyGalleryActivity extends Activity {

	private AmazonS3Client s3Client = new AmazonS3Client(
			new BasicAWSCredentials(Constants.ACCESS_KEY_ID,
					Constants.SECRET_KEY));

	private List<String> list = new ArrayList<String>();
	private List<String> namelist = new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	
		try {
		
			new MyGalleryTask().execute().get();
		
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		try {
			display();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

	private class bitmapTask extends AsyncTask<String,Void,Drawable>{

		@Override
		protected Drawable doInBackground(String... params) {
			// TODO Auto-generated method stub
			String url = params[0];
					
			try {
				
	    		InputStream content = (InputStream)new URL(url).getContent();
	    		return Drawable.createFromStream(content, "src");
				
				//return BitmapFactory.decodeStream((InputStream) new URL(url).getContent());
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
			
		}

			
	}
	
	
	private void display() throws MalformedURLException, IOException{
		TableLayout tl=new TableLayout(this);
		
		TextView title = new TextView(this);
		title.setText("\tPhoto Gallery\t");
		title.setTextColor(Color.DKGRAY);
		title.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
		title.setWidth(350);
		title.setHeight(100);
		
		title.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT));
	    tl.addView(title);
		
		for(int i = 0 ; i < list.size();i++) 
		{
										
			TableRow tr = new TableRow(this);

			tr.setPadding(0,20,0,20);
		
		    tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT));

//		    ImageView imgView = new ImageView(this);
		    TextView tv = new TextView(this);
					    
		    
		    SpannableString ss = new SpannableString(namelist.get(i));
            ss.setSpan(new StyleSpan(Typeface.ITALIC), 0, namelist.get(i).length(),
                    		Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ss.setSpan(new URLSpan(list.get(i)), 0, namelist.get(i).length(),
                    		Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ss.setSpan(new ForegroundColorSpan(Color.RED),0, namelist.get(i).length(), 
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);        
            
            tv.setMovementMethod(LinkMovementMethod.getInstance());
            tv.setText(ss);
		    
	    
//		    Bitmap bitmap;
//			try {
//		
//				bitmap = new bitmapTask().execute(list.get(i)).get();
//				imgView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT));
//				imgView.setImageBitmap(bitmap);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (ExecutionException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		    
	        System.gc();

	        
//	        Drawable drawable = null;
//			try {
//				drawable = new bitmapTask().execute(list.get(i)).get();
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (ExecutionException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} 
//	        imgView.setImageDrawable(drawable);
//	 	    		    		    				    
//			tr.addView(imgView);
	
	        tr.addView(tv);

						    
		    tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    
		}
		
		LinearLayout ll=new LinearLayout(this);
		ScrollView sv=new ScrollView(this);
		
		sv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT));
		sv.addView(tl);
		
		ll.addView(sv);
		
		setContentView(ll);

	}
	

	
	private class MyGalleryTask extends AsyncTask<Void, Void, Void> {
		
		protected Void doInBackground(Void... voids) {

			ObjectListing ol = s3Client.listObjects(Constants.getPictureBucket());
			List<S3ObjectSummary> los = ol.getObjectSummaries();
			
			ObjectListing next = s3Client.listNextBatchOfObjects(ol);
			
			los.addAll(next.getObjectSummaries());

			while (next.isTruncated()) {
			   ol=s3Client.listNextBatchOfObjects(next);
			   los.addAll(ol.getObjectSummaries());
			   next =s3Client.listNextBatchOfObjects(ol);
			}
			los.addAll(next.getObjectSummaries());

		
			for(int i=0;i<los.size();i++)
			{
				String picName = los.get(i).getKey();
				S3Object obj = s3Client.getObject(Constants.getPictureBucket(),picName);
			
												
				ResponseHeaderOverrides override = new ResponseHeaderOverrides();
				override.setContentType("image/jpeg");
				
				Date expirationDate = new Date(System.currentTimeMillis() + 3600000);
				GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(
						Constants.getPictureBucket(),picName);
				urlRequest.setExpiration(expirationDate);
				urlRequest.setResponseHeaders(override);

				URL url = s3Client.generatePresignedUrl(urlRequest);

				list.add(url.toString());
				namelist.add(picName);
				Log.d("KEYSSSSSS",url.toString());
										
			}
			return null;
		}

	}
	
}
